package cn.itcast.interceptors;

import jdk.nashorn.internal.ir.annotations.Ignore;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component//将这个拦截器放入到ioc容器中
public class MyEasyInterceptor implements HandlerInterceptor {
    //拦截器的拦截方法,会在控制器方法执行的情况前执行,用于前置增加例如:登录操作
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle执行了");
       /* 当请求的地址包含login即登录请求放行
       if(request.getRequestURL().toString().contains("login")){
            return true;
        }*/
        HttpSession session = request.getSession();
        String name = (String)session.getAttribute("meto");
        System.out.println("444"+name);
        if (name == null){
            //没有登录
            response.sendRedirect(request.getContextPath()+"/login.jsp");
            return false;
        }
        return true;
    }
    //这是拦截器的后处理方法,执行时机为在控制器方法之后,返回视图之前
    //可以对响应数据进行增强
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle执行了");

        /*String meto = (String)request.getAttribute("meto");
        if (!StringUtils.isEmpty(meto)){}
        meto = meto.replace("itcast", "**");
        request.removeAttribute("meto");
        request.setAttribute("meto",meto);*/
    }
    //这是拦截器最后执行的方法,返回视图结果后,响应之前
    //可以实现一些清理的操作
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion执行了");
    }
}
